<!-- 加油卡管理 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属部门" prop="companyId">
        <el-tree-select v-model="queryParams.companyId" placeholder="请选择所属公司" clearable :data="treeList"
          :expand-on-click-node="false" :render-after-expand="false" @change="handleQuery" check-strictly
          :props="{ label: 'label' }" node-key="id" filterable />
      </el-form-item>
      <el-form-item label="油卡编号" prop="oilNum">
        <el-input v-model="queryParams.oilNum" placeholder="请输入油卡编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="购买时间" prop="buyTime">
        <el-date-picker clearable v-model="queryParams.buyTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择购买时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['gwc:carManagement:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['gwc:carManagement:edit']">修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="Select" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['gwc:etcManagement:remove']">启用</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="CloseBold" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['gwc:etcManagement:remove']">禁用</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['gwc:carManagement:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['gwc:carManagement:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="managementList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="所属公司" align="center" prop="companyName"></el-table-column>
      <el-table-column label="加油卡卡号" align="center" prop="oilNum"></el-table-column>
      <el-table-column label="购买时间" align="center" prop="buyTime" width="180"></el-table-column>
      <el-table-column label="金额(元)" align="center" prop="amountStr"></el-table-column>
      <el-table-column label="里程(km)" align="center" prop="mileageStr"></el-table-column>
      <el-table-column label="备注说明" align="center" prop="remarks"></el-table-column>
      <el-table-column label="绑定车辆" align="center" prop="numberPlate"></el-table-column>
      <el-table-column label="操作" width="440" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row, 'edit')"
            v-hasPermi="['gwc:etcManagement:edit']">修改</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row, 'detail')"
            v-hasPermi="['gwc:etcManagement:edit']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleTopUp(scope.row)"
            v-hasPermi="['gwc:etcManagement:edit']">充值</el-button>
          <el-button link type="primary" icon="Edit" @click="handleTopUpDetail(scope.row)"
            v-hasPermi="['gwc:etcManagement:edit']">充值记录</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['gwc:etcManagement:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改加油卡管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="managementRef" :model="form" :rules="rules" label-width="80px" class="sky-form-block"
        :disabled="formType == 'detail'">
        <el-form-item label="所属公司" prop="companyId">
          <el-tree-select v-model="form.companyId" placeholder="请选择所属公司" clearable :data="treeList"
            :props="{ label: 'label' }" node-key="id" filterable />
        </el-form-item>
        <el-form-item label="油卡编号" prop="oilNum">
          <el-input v-model="form.oilNum" placeholder="请输入油卡编号" />
        </el-form-item>
        <el-form-item label="购买时间" prop="buyTime">
          <el-date-picker clearable v-model="form.buyTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择购买时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="金额(元)" prop="amountStr">
          <el-input v-model="form.amountStr" placeholder="请输入金额" :disabled="formType == 'edit'" />
        </el-form-item>
        <el-form-item label="车辆" prop="vehicleId">
          <el-select v-model="form.vehicleId" filterable remote reserve-keyword placeholder="请输入车牌号查询"
            :remote-method="remoteMethod" :loading="remoteLoading">
            <el-option v-for="item in sel_option.vehicleId" :key="item.id" :label="item.numberPlate" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="里程(km)" prop="mileageStr">
          <el-input v-model="form.mileageStr" placeholder="请输入里程" />
        </el-form-item>
        <el-form-item label="备注说明" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 充值 -->
    <el-dialog title="充值" v-model="topUpOpen" width="500px" class="top-up-window">
      <el-form ref="managementTopUpRef" :model="upTopForm" :rules="rules" label-width="80px" class="sky-form-block">
        <el-form-item label="金额(元)" prop="amountStr">
          <el-input-number v-model="upTopForm.amountStr" :precision="2" :step="0.01" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="备注说明" prop="remarks">
          <el-input v-model="upTopForm.remarks" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="topUpSubmitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 充值记录 -->
    <el-dialog :title="'充值记录-' + recordQueryParams.oilNum" v-model="topUpDetailOpen" width="1200px" append-to-body>
      <el-form :model="recordQueryParams" ref="recordQueryRef" :inline="true" v-show="showSearch" label-width="68px">
        <searchType v-for="v in searchProps" :data="v" :selects="sel_option[v.prop]" v-model="recordQueryParams[v.prop]"
          :handleQuery="recordHandleQuery">
        </searchType>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="recordHandleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="recordResetQuery">重置</el-button>
          <el-button type="warning" plain icon="Download" @click="recordhandleExport">导出</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange" style="height: 600px;">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="所属公司" align="center" prop="companyName"></el-table-column>
        <el-table-column label="车牌号" align="center" prop="numberPlate"></el-table-column>
        <el-table-column label="发生时间" align="center" prop="buyTime" width="180"></el-table-column>
        <el-table-column label="费用类型" align="center" prop="costType">
          <template #default="scope">
            <dict-tag :options="sel_option.costType" :value="scope.row.costType" />
          </template>
        </el-table-column>
        <el-table-column label="费用名称" align="center" prop="costName">
          <template #default="scope">
            <dict-tag :options="sel_option.costName" :value="scope.row.costName" />
          </template>
        </el-table-column>
        <el-table-column label="金额(元)" align="center" prop="amountStr"></el-table-column>
        <el-table-column label="费用说明" align="center" prop="remarks" width="180"></el-table-column>
      </el-table>
      <pagination :total="recordTotal" v-model:page="recordQueryParams.pageNum" v-model:limit="recordQueryParams.pageSize"
        @pagination="getList" />
    </el-dialog>
  </div>
</template>

<script setup name="Management" lang="ts">
import { listManagement, getManagement, delManagement, addManagement, updateManagement } from "@/api/gwc/carManagement";
import { getSearchCompanyListRole } from "@/api/system/dept";
import { addRecord, listRecord } from "@/api/gwc/costRecord";
import { getVehicleList } from "@/api/tool/gen"
const { proxy } = getCurrentInstance() as any;

const managementList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const names = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const treeList = ref([])
getSearchCompanyListRole().then(res => {
  treeList.value = res.data
})

const sel_option = ref<any>({});

const recordList = ref([]);
const topUpDetailOpen = ref(false);
const recordTotal = ref(0);

const recordQueryParams = ref({
  pageNum: 1,
  pageSize: 15,
}) as any;


const data = reactive({
  form: {} as any,
  queryParams: {
    pageNum: 1,
    pageSize: 15,
    companyId: null,
    oilNum: null,
    buyTime: null,
    remarks: null,
    mileageStr: null,
    amountStr: null,
  },
  rules: {
    companyId: [
      { required: true, message: "所属部门不能为空", trigger: "blur" }
    ],
    oilNum: [
      { required: true, message: "卡号不能为空", trigger: "blur" }
    ],
  }
});
let dictList = [];
sel_option.value = proxy.useDict.apply(this, [...dictList, "gasCardOrderStatus", "costType", "costName"]);
const { queryParams, form, rules } = toRefs(data);
import { searchComponentType } from "@/components/tableRelate/searchTypeTs"
import dayjs from "dayjs"
const searchProps = reactive([
  { label: "费用名称", prop: "costName", type: searchComponentType.select },
  { label: "费用类型", prop: "costType", type: searchComponentType.select },
  { label: "充值时间", prop: "buyTime", type: searchComponentType.dateTime },
])
const formType = ref('add');
const upTopForm = ref<{
  companyId: string,
  vehicleId: string,
  driverId: string,
  costType: number,
  costName: number
  fuelId: string,
  remarks: string,
  amountStr: string
}>({
  companyId: null,
  vehicleId: null,
  driverId: null,
  costType: null,
  costName: null,
  fuelId: null,
  remarks: null,
  amountStr: null,
})
const topUpOpen = ref(false);
const remoteLoading = ref(true);
const remoteMethod = (queryStr: string) => {
  remoteLoading.value = true
  if (queryStr) {
    getVehicleList({
      pageNum: 1,
      pageSize: 10,
      companyId: form.value.companyId, //公司id
      numberPlate: queryStr, //车牌号（支持模糊匹配）
    }).then((res: any) => {
      remoteLoading.value = false;
      sel_option.value.vehicleId = res.rows
    })
  }
}


/** 查询加油卡管理列表 */
function getList() {
  loading.value = true;
  listManagement(queryParams.value).then((response: any) => {
    managementList.value = response.rows
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  topUpOpen.value = false;
  topUpDetailOpen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    fuelId: null,
    companyId: null,
    oilNum: null,
    buyTime: null,
    remarks: null,
    mileageStr: null,
    amountStr: null,
    orderStatus: null,
    createTime: null,
    updateTime: null,
    updateBy: null,
    createBy: null
  };
  proxy.resetForm("managementRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
function recordHandleQuery() {
  recordQueryParams.value.pageNum = 1;
  handleTopUpDetail(null);
}


/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
function recordResetQuery() {
  proxy.resetForm("recordQueryRef");
  recordHandleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  names.value = selection.map(item => item.oilNum);
  ids.value = selection.map(item => item.fuelId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加加油卡管理";
}

/** 修改按钮操作 */
function handleUpdate(row, param) {
  formType.value = param;
  reset();
  form.value = row;
  open.value = true;
  if (param == 'detail') {
    title.value = "查看加油卡";
  } else if (param == 'edit') {
    title.value = "修改加油卡";
  }
  sel_option.value.vehicleId = [
    {
      id: row.vehicleId,
      numberPlate: row.numberPlate,
    }
  ]
}

// 充值
function handleTopUp(row) {
  upTopForm.value.companyId = row.companyId
  upTopForm.value.vehicleId = row.vehicleId
  upTopForm.value.driverId = row.driverId
  upTopForm.value.costType = 0
  upTopForm.value.costName = 0
  upTopForm.value.fuelId = row.fuelId
  upTopForm.value.amountStr = '0.0'
  topUpOpen.value = true;
}

// 充值记录
function handleTopUpDetail(row) {
  if (row) {
    recordQueryParams.value.fuelId = row.fuelId
    recordQueryParams.value.oilNum = row.oilNum
  }
  const query = {
    ...recordQueryParams.value
  }
  if (recordQueryParams.value?.buyTime?.length > 0) {
    query.startTime = recordQueryParams.value?.buyTime[0]
    query.endTime = recordQueryParams.value?.buyTime[1]
    delete query.buyTime // 删除多选查询的buyTime
  }
  listRecord(query).then((res: any) => {
    recordList.value = res.rows;
    recordTotal.value = res.total
    topUpDetailOpen.value = true;
  })
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["managementRef"].validate(valid => {
    if (valid) {
      if (form.value.fuelId != null) {
        form.value.amountStr = '0.0';
        updateManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function topUpSubmitForm() {
  proxy.$refs["managementTopUpRef"].validate(valid => {
    if (valid) {
      addRecord(upTopForm.value).then(response => {
        proxy.$modal.msgSuccess("充值成功");
        cancel();
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _fuelIds = row.fuelId || ids.value;
  const str = row.oilNum || names.value;
  proxy.$modal.confirm('是否确认删除加油卡卡号为"' + str + '"的数据项？').then(function () {
    return delManagement(_fuelIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('gwc/carManagement/export', {
    ...queryParams.value
  }, `加油卡管理_${dayjs(new Date()).format("YYYY-MM-DD_HH:mm:ss")}.xlsx`)
}
function recordhandleExport() {
  const query = {
    ...recordQueryParams.value
  }
  if (recordQueryParams.value?.buyTime?.length > 0) {
    query.startTime = recordQueryParams.value?.buyTime[0]
    query.endTime = recordQueryParams.value?.buyTime[1]
    delete query.buyTime // 删除多选查询的buyTime
  }
  proxy.download('gwc/costRecord/export', query, `加油卡充值记录_${new Date().getTime()}.xlsx`)
}
getList();
</script>
<style scoped lang="scss">
:deep(.top-up-window) {
  margin-top: 30vh;
}
</style>